import logging

import neon.scheduler as scheduler

# Comment this out to not have any logging output
# logging.basicConfig(level = logging.DEBUG)

CUR_TIME = 0

def get_time():
    return CUR_TIME
scheduler.get_time = get_time

q = scheduler.Queue('test1', 1)

q.append('msg1')
q.append('msg2')
q.prepend('msg3')

assert q.msgs_ == ['msg2', 'msg1', 'msg3']

q.after_interval('msg4', 1)
q.after_interval('msg5', 2)

assert q.timeout() is None

CUR_TIME = 1.5
assert q.timeout() == 'msg4'
assert q.timeout() is None

CUR_TIME = 3
assert q.pull() == 'msg5'
assert q.timeout() is None

assert q.pull() == 'msg3'
assert q.pull() == 'msg1'
assert q.pull() == 'msg2'
assert q.pull() is None

class MySched(scheduler.Scheduler):
    def match_scheme(self, tx_type, iface_id, peer_id):
        return iface_id

    def send(self, msg, iface_id, peer_id):
        global RET
        RET = (msg, iface_id, peer_id)

RET = None

schd = MySched()
schd.add_queue(q)
schd.add_queue(scheduler.Queue('test2', 0))

schd.add_scheme(scheduler.Scheme('scheme1', ['test1', 'test2']))
schd.add_scheme(scheduler.Scheme('scheme2', ['test1']))

schd.schedule_msg('MSG 1', 'test1')
schd.schedule_msg('MSG 2', 'test1')
schd.schedule_msg('MSG 3', 'test1')
schd.schedule_msg('MSG 4', 'test2')
schd.schedule_msg('MSG 5', 'test2')

assert schd.pull_data('scheme1') == 'MSG 4'
assert schd.pull_data('scheme2') == 'MSG 1'
assert schd.pull_data('scheme1') == 'MSG 5'
assert schd.pull_data('scheme2') == 'MSG 2'
assert schd.pull_data('scheme2') == 'MSG 3'
assert schd.pull_data('scheme2') is None

assert RET is None

schd.schedule_msg('MSG 1', 'test1')
schd.schedule_msg('MSG 2', 'test1')
schd.schedule_msg('MSG 3', 'test1')
schd.schedule_msg('MSG 4', 'test2')
schd.schedule_msg('MSG 5', 'test2')

assert RET is None

schd.req_data('tx_type','scheme1', 'peer1')
assert RET == ('MSG 4', 'scheme1', 'peer1')
schd.req_data('tx_type','scheme2', 'peer2')
assert RET == ('MSG 1', 'scheme2', 'peer2')
schd.req_data('tx_type','scheme2', 'peer2')
assert RET == ('MSG 2', 'scheme2', 'peer2')
schd.req_data('tx_type','scheme2', 'peer2')
assert RET == ('MSG 3', 'scheme2', 'peer2')
schd.req_data('tx_type','scheme1', 'peer1')
assert RET == ('MSG 5', 'scheme1', 'peer1')
RET = None

schd.req_data('tx_type','scheme1', 'peer1')
assert RET is None
schd.req_data('tx_type','scheme2', 'peer2')
assert RET is None

schd.schedule_msg('MSG 6', 'test1')
assert RET == ('MSG 6', 'scheme1', 'peer1')
schd.schedule_msg('MSG 7', 'test1')
assert RET == ('MSG 7', 'scheme2', 'peer2')
schd.req_data('tx_type','scheme1', 'peer1')
schd.schedule_msg('MSG 8', 'test1')
assert RET == ('MSG 8', 'scheme1', 'peer1')

